package org.osami.backoffice.eventswitch;

import javax.annotation.Resource;
import javax.jms.*;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: guillaume
 * Date: 22/09/11
 * Time: 11:40
 * To change this template use File | Settings | File Templates.
 */
public class Main {

    @Resource(mappedName = "SenseDataQueue")
    private static Queue senseDataQueue;

    @Resource(mappedName = "AlarmQueue")
    private static Queue alarmQueue;

    @Resource(mappedName = "QCF")
    private static QueueConnectionFactory factory;

    public static void main(String[] args) throws Exception {

        System.out.println("Obtaining JMS Objects ...");

        QueueConnection qc = factory.createQueueConnection();
        QueueSession session = qc.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
        QueueSender sender = session.createSender(senseDataQueue);

        System.out.print("Sending SenseData messages ");

        qc.start();

        double value = 0;

        for (int i = 0; i < 50; i++) {

            // separate each value in the time by 1 second
            HashMap<String, Serializable> data = createSenseData(value + 0.5, i * 1000);

            System.out.print(".");

            ObjectMessage message = session.createObjectMessage();
            message.setObject(data);
            sender.send(message);

        }

        sender.close();

        sender = session.createSender(alarmQueue);


        // Creates one alarm
        HashMap<String, Serializable> alarm = createAlarm("Something is rotten in the state of Denmark.");

        ObjectMessage message = session.createObjectMessage();
        message.setObject(alarm);
        sender.send(message);
        sender.close();

        session.close();
        qc.stop();

        System.out.println();



        System.out.println("Done !");

    }

    private static HashMap<String, Serializable> createSenseData(double value, long offset) {
        HashMap<String, Serializable> data = new HashMap<String, Serializable>();
        data.put("location", "127.0.0.1");
        data.put("sense.id", "1234");
        data.put("type", "luminosity");
        data.put("timestamp", System.currentTimeMillis() + offset);
        data.put("value", Double.valueOf(value));
        return data;
    }

    private static HashMap<String, Serializable> createAlarm(String message) {
        HashMap<String, Serializable> data = new HashMap<String, Serializable>();

        data.put("alarm.id", "there-can-be-only-one");
        data.put("alarm.date", new Date(System.currentTimeMillis()));
        data.put("alarm.message", message);
        data.put("alarm.severity", "warning");

        data.put("source", "127.0.0.1");
        data.put("type", "luminosity");
        data.put("threshold", Double.valueOf(100));
        data.put("value", Double.valueOf(125));
        return data;
    }
}
